package com.cg.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cg.dto.AddUserDTO;
import com.cg.dto.SearchUserDTO;
import com.cg.entity.User;
import com.cg.mapper.UserMapper;
import com.cg.result.R;
import com.cg.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cg.service.UserService;
import com.cg.utils.Md5Utils;
import com.cg.vo.PageVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author 加
 * @since 2025-01-17
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    private IUserService userService;
    @Autowired
    private UserService userService2;
    @Override
    public R<List<User>> getUserByCondition(SearchUserDTO searchUserDTO) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.like(searchUserDTO.getName()!=null,User::getName,searchUserDTO.getName())
                .like(searchUserDTO.getPhone()!=null,User::getName,searchUserDTO.getPhone())
                .eq(searchUserDTO.getStatus()!=null,User::getStatus,searchUserDTO.getStatus());

        Page<User> userPage=new Page<>(searchUserDTO.getPageNumber(),searchUserDTO.getPageSize());
        userPage=page(userPage,queryWrapper);
        PageVO<User> userPageVO=new PageVO<>();
        BeanUtils.copyProperties(userPage,userPageVO);
        return R.Success(userPageVO);
    }

    @Override
    public R addUser(AddUserDTO addUserDTO) {
            if(addUserDTO.getName()==null||addUserDTO.getName().isEmpty()){
                return R.Failed("新增失败，用户姓名不能为空");
            }
            if(addUserDTO.getStatus()==null){
                return R.Failed("新增失败，用户状态不能为空");
            }
            String phoneNumber = addUserDTO.getPhone();
            Map<String, List<User>> phone2 = userService.phoneList();
            if (phoneNumber == null || phoneNumber.length() < 6) {
                return R.Failed("电话号码无效");
            }
            if (phone2.containsKey(phoneNumber)) {
                return R.Failed("电话号码唯一，不可重复");
            }
            String password = phoneNumber.substring(phoneNumber.length() - 6);
            byte[] password2= Md5Utils.md5(password);
            String password3=Md5Utils.toHex(password2);
            User user = new User();
            user.setName(addUserDTO.getName());
            user.setStatus(addUserDTO.getStatus());
            user.setPhone(addUserDTO.getPhone());
            System.out.println("电话号码为：" + user.getPhone());
            user.setPassword(password3);
            user.setCreateTime(LocalDateTime.now());

       /* String loginAccount;
        long seq;
        Map<String, List<User>> listMap = userService.userNameList();
        do {

            seq = userService2.loginAccountSequence.incrementAndGet();
            loginAccount = "YZ" + String.format("%04d", seq);
        } while (listMap.containsKey(loginAccount));
       loginAccount=loginAccount;
       user.setUserName(loginAccount);
       save(user);*/

            String loginAccount;
            long seq;
            Map<String, List<User>> userNameList = userService.accountList();
            do {
                seq = userService2.loginAccountSequence.incrementAndGet();
                loginAccount = "YZ" + String.format("%04d", seq);
            } while (userNameList.containsKey(loginAccount));

            user.setCreateTime(LocalDateTime.now());
            user.setAccount(loginAccount);
            save(user);
            try {
                return R.Success("新增成功");
            } catch (Exception e) {
                return R.Failed("保存用户失败：" + e.getMessage());
            }
    }


    @Override
    public Map<String,List<User>> phoneList() {
        List<User> list=userService.list();
        Map<String,List<User>> phoneMap=list.stream()
                .collect(Collectors.groupingBy(User::getPhone));
        return phoneMap;
    }

    @Override
    public Map<String,List<User>> accountList() {
        List<User> list=userService.list();
        Map<String,List<User>> userNameMap=list.stream()
                .collect(Collectors.groupingBy(User::getAccount));
        return userNameMap;
    }

    @Override
    public R deleteUser(Long userId) {
        User user=getById(userId);
        removeById(user);
        return R.Success("删除用户成功");
    }
}
